package com.lanyou.cook.camel.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.camel.CamelContext;
import org.apache.camel.component.quartz2.QuartzComponent;
import org.apache.log4j.Logger;

import com.lanyou.cook.camel.commons.Constants;
import com.lanyou.cook.camel.dao.impl.FtpDao;
import com.lanyou.cook.camel.dao.impl.FtpServerDao;
import com.lanyou.cook.camel.dao.impl.ScheduleDao;
import com.lanyou.cook.camel.entity.Ftp;
import com.lanyou.cook.camel.entity.FtpServer;
import com.lanyou.cook.camel.entity.TesbBuIfSchedule;
import com.lanyou.cook.camel.exception.AuthException;
import com.lanyou.cook.camel.service.CamelService;
import com.lanyou.cook.camel.util.CamelFactory;
import com.lanyou.cook.camel.util.ExceptionToStrFactory;
import com.lanyou.cook.camel.util.FTPCamelRouteBuilder;
import com.lanyou.cook.camel.util.FtpComponentChild;

/**
 * 对外接口CamelService的实现
 * 
 * @author ly-lihailang
 *
 */
public class CamelServiceImpl implements CamelService {
	private static Logger logger = Logger.getLogger(CamelServiceImpl.class);

	private FtpServerDao ftpServerDao;

	private ScheduleDao scheduleDao;

	private FtpDao ftpDao;

	private AuthServiceImpl authServiceImpl;

	private LogServiceImpl logServiceImpl;

	@Override
	public void createAndStartCamel(String camelId) {
		logger.info("[CamelServiceImpl.createAndStartCamel]:camelId="+camelId);
		// 创建camelContext实例
		CamelContext camelContext = CamelFactory.ctreatCamel(camelId);
		try {
			// 根据接口编号获取FTP服务接口
			Ftp ftp = ftpDao.findByCode(camelId);
			if (ftp == null) {
				logger.error("[CamelServiceImpl.createAndStartCamel]:接口：---" + camelId + "--在数据库中找不到");
				throw new AuthException(Constants.MSG_INTERFACE_NOTFOUND,
						Constants.CODE_INTERFACE_NOTFOUND);
			}else{
				CamelFactory.ftpMap.put(camelId, ftp);
			}
			// 根据FTP服务接口id获取到该服务下的所有ftp服务
			List<FtpServer> ftpServerList = ftpServerDao
					.findFtpServersByFtpId(ftp.getId());
			if (ftpServerList == null || ftpServerList.size() == 0) {
				logger.error("[CamelServiceImpl.createAndStartCamel]:接口：---" + camelId + "--在数据库中找不到对应的ftp服务");
				return;
			}
			// 根据FTP服务接口id获取到该服务接口定时任务
			TesbBuIfSchedule buIfSchedule = null;
			if (ftp.getIsSchedule().equals("1")) {
				buIfSchedule = scheduleDao.findTesbBuIfScheduleByifId(ftp
						.getId());
				if (buIfSchedule == null) {
					logger.error("[CamelServiceImpl.createAndStartCamel]:接口：---"+ camelId + "--在数据库中找不到对应的定时任务");
					return;
				}
			}
			if (camelContext.getRoutes().size() < 1) {
				// 将FTP接口、FTP服务、定时任务的参数注入路由
				FTPCamelRouteBuilder fTPCamelRouteBuilder = new FTPCamelRouteBuilder(
						ftpServerList, buIfSchedule, ftp);
				fTPCamelRouteBuilder.setAuthServiceImpl(authServiceImpl);
				fTPCamelRouteBuilder.setLogServiceImpl(logServiceImpl);
				// 往camelContext中添加创建好的路由
				camelContext.addRoutes(fTPCamelRouteBuilder);
				logger.info("[CamelServiceImpl.createAndStartCamel]:"+fTPCamelRouteBuilder);
			}

			// 如果存在，则判断其中的ftp、quartz2路由样式是否存在，不存在自动添加
			if (camelContext.getComponent("ftp") == null) {
				camelContext.addComponent("ftp", new FtpComponentChild());
			}
			if (camelContext.getComponent("quartz2") == null) {
				camelContext.addComponent("quartz2", new QuartzComponent());
			}
			// 启动camelContext
			if (CamelFactory.isLeader) {
				camelContext.start();
			}
		} catch (Exception e) {
			logger.error("[CamelServiceImpl.createAndStartCamel]:"+ExceptionToStrFactory.getErrorInfoFromException(e));
		}
	}

	@Override
	public void startCamel(String camelId) {
		// 根据接口编号获取camelContext
		CamelContext camelContext = CamelFactory.getCamel(camelId);
		try {
			if (camelContext == null) {// 如果没有则创建并启动
				createAndStartCamel(camelId);
			} else {// 如果存在，则判断其中的ftp、quartz2路由样式是否存在，不存在自动添加
				if (camelContext.getComponent("ftp") == null) {
					camelContext.addComponent("ftp", new FtpComponentChild());
				}
				if (camelContext.getComponent("quartz2") == null) {
					camelContext.addComponent("quartz2", new QuartzComponent());
				}
				// 启动camelContext
				if (CamelFactory.isLeader) {
					camelContext.start();
				}
			}
		} catch (Exception e) {
			logger.error("[CamelServiceImpl.startCamel]:"+ExceptionToStrFactory.getErrorInfoFromException(e));
		}

	}

	@Override
	public void stopCamel(String camelId) {
		// 根据接口编号获取camelContext
		CamelContext camelContext = CamelFactory.getCamel(camelId);
		try {
			if (camelContext != null) {// 不为空则停止
				camelContext.stop();
			}
		} catch (Exception e) {
			logger.error("[CamelServiceImpl.stopCamel]:"+ExceptionToStrFactory.getErrorInfoFromException(e));
		}

	}

	@Override
	public void delCamel(String camelId) {
		// 根据接口编号获取camelContext
		CamelContext camelContext = CamelFactory.getCamel(camelId);

		if (camelContext != null && !camelContext.getStatus().isStopped()) {// 若状态为未停止，则先停止再删除
			try {
				camelContext.stop();
				CamelFactory.camelMap.remove(camelId);
			} catch (Exception e) {
				logger.error("[CamelServiceImpl.delCamel]:"+ExceptionToStrFactory.getErrorInfoFromException(e));
			}
		} else {// 删除camelContext
			CamelFactory.camelMap.remove(camelId);
		}

	}

	@Override
	public void init() {
		// 获取已审核的接口
		List<String> strList = getAllFtpCode();
		// 轮循启动已审核接口
		for (String id : strList) {
			restartCamel(id);
		}

	}

	@Override
	public Map<String, CamelContext> getAllCamelContext() {

		return CamelFactory.camelMap;
	}

	@Override
	public List<String> getAllFtpCode() {
		// 创建一个封装查询条件的实例
		Ftp ftp = new Ftp();
		// 给实例的审核状态赋值，1：已审核的
		ftp.setAuditStatus("1");
		// 启动的
		ftp.setStatus("1");
		// 可用的
		ftp.setIsEnable("1");
		// 调度的
		ftp.setIsSchedule("1");
		// 取出所有已审核的接口
		List<Ftp> ftpList = ftpDao.findByWhere(ftp);
		List<String> strList = new ArrayList<String>();
		// 将接口id存入List
		for (Ftp ftp1 : ftpList) {
			strList.add(ftp1.getCode());
		}
		return strList;
	}

	@Override
	public void restartCamel(String camelId) {
		// 删除已创建的camelContext
		delCamel(camelId);
		// 创建、启动camelContext
		startCamel(camelId);
	}

	@Override
	public void close() {
		// 获取已审核的接口
		List<String> strList = getAllFtpCode();
		// 轮循启动已审核接口
		for (String id : strList) {
			delCamel(id);
		}

	}

	public FtpServerDao getFtpServerDao() {
		return ftpServerDao;
	}

	public void setFtpServerDao(FtpServerDao ftpServerDao) {
		this.ftpServerDao = ftpServerDao;
	}

	public ScheduleDao getScheduleDao() {
		return scheduleDao;
	}

	public void setScheduleDao(ScheduleDao scheduleDao) {
		this.scheduleDao = scheduleDao;
	}

	public FtpDao getFtpDao() {
		return ftpDao;
	}

	public void setFtpDao(FtpDao ftpDao) {
		this.ftpDao = ftpDao;
	}

	public AuthServiceImpl getAuthServiceImpl() {
		return authServiceImpl;
	}

	public void setAuthServiceImpl(AuthServiceImpl authServiceImpl) {
		this.authServiceImpl = authServiceImpl;
	}

	public LogServiceImpl getLogServiceImpl() {
		return logServiceImpl;
	}

	public void setLogServiceImpl(LogServiceImpl logServiceImpl) {
		this.logServiceImpl = logServiceImpl;
	}

}
